package com.jfinal.ext.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.platform.tools.ToolHttp;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

public class BaiduApi {
    private static String API = "http://api.map.baidu" +
            ".com/geocoder/v2/?address=<address>&output=json&ak=20HO9VWIlnsREA1ikvhhFYNfj0HNixXv";


    /*
    result:
    {"status":0,"result":{"location":{"lng":103.49773846901363,"lat":30.239938504594034},"precise":0,"confidence":16,"level":"区县"}}
     */


    public static String[] addressToGPS(String address) {
        try {
            String requestUrl = API.replaceAll("<address>", URLEncoder.encode(address, "UTF-8"));
            System.out.println("请求地址: {}" + requestUrl);
            String result = ToolHttp.post(true, requestUrl, null, "1");
            if (result != null) {
                System.out.println(result);
                Map<String, Object> map = (Map<String, Object>) JSON.parse(result);
                int s = (int) map.getOrDefault("status", 1);
                if (s == 0) {
                    JSONObject rs = (JSONObject) map.get("result");
                    JSONObject loc = rs.getJSONObject("location");
                    System.out.println(loc);
                    return new String[]{loc.getString("lng"), loc.getString("lat")};
                }
            }
        } catch (UnsupportedEncodingException e) {
        }

        return null;
    }

    public static void main(String[] args) {
        System.out.println(BaiduApi.addressToGPS("陕西省西安市雁塔区徐家庄村"));
    }
}

